package com.martini.satoken01.controller;

import com.martini.satoken01.entity.SysUser;
import com.martini.satoken01.model.AjaxJson;
import com.martini.satoken01.model.dto.UserRegInfoDTO;
import com.martini.satoken01.model.mapper.SysUserEntityMapper;
import com.martini.satoken01.service.system.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 注册控制器
 *
 * @author martini at 2021/12/19 9:49
 */
@Slf4j
@RestController
@RequestMapping("/register")
public class RegisterController {

    private UserService userService;

    private SysUserEntityMapper sysUserEntityMapper;

    public RegisterController(UserService userService, SysUserEntityMapper sysUserEntityMapper) {
        this.userService = userService;
        this.sysUserEntityMapper = sysUserEntityMapper;
    }

    @PostMapping
    public AjaxJson registerUser(@RequestBody @Valid UserRegInfoDTO userRegInfoDTO, BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {
            return AjaxJson.fail().setMsg("参数错误，请检查参数是否合法");
        }
        SysUser sysUser = sysUserEntityMapper.toSysUser(userRegInfoDTO);
        boolean addSuccessfully = userService.addUser(sysUser);
        return addSuccessfully ? AjaxJson.success().setMsg("注册成功") : AjaxJson.fail().setMsg("注册失败，用户名可能已被注册");
    }

}
